/**
 * 
 */
package com.teamall.web.xtgl.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.teamall.core.common.Page;
import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.exception.ExceptionHandler;
import com.teamall.framework.log.LogManager;
import com.teamall.framework.util.Utils;
import com.teamall.web.family.customdb.arg.CustomCodeFamilyInfoArg;
import com.teamall.web.family.customdb.dao.CustomFamilyAndMemberDao;
import com.teamall.web.family.db.po.FamilyInfoPO;
import com.teamall.web.family.db.po.FamilyMemberPO;
import com.teamall.web.family.service.IFamilyInfoService;
import com.teamall.web.family.service.IFamilyMemberService;
import com.teamall.web.fpgz.db.arg.CodeFamilyInfoArg;
import com.teamall.web.fpgz.db.arg.CodeFamilyInfoArg.CodeFamilyInfoCriteria;
import com.teamall.web.fpgz.db.po.CodeFamilyInfoPO;
import com.teamall.web.xtgl.common.ImpDataResultVO;
import com.teamall.web.xtgl.common.StaticDataUtil;
import com.teamall.web.xtgl.service.IBasicDataService;

/**
 * <Description> <br>
 * 
 * @author pan.xiaobo<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2017年8月17日 <br>
 * @since V1.0<br>
 * @see com.teamall.web.xtgl.service.impl <br>
 */
@Service("basicDataService")
public class BasicDataServiceImpl implements IBasicDataService {
    public static final String ACTIONADD = "ADD";

    public static final String ACTIONUPDATE = "UPDATE";

    private static final LogManager logger = LogManager
            .getLogger(BasicDataServiceImpl.class);

    @Autowired
    private IFamilyInfoService familyInfoService;

    @Autowired
    private IFamilyMemberService familyMemberService;

    @Autowired
    private CustomFamilyAndMemberDao customFamilyAndMemberDao;

    /*
     * (non-Javadoc)
     * @see com.teamall.web.xtgl.service.IBasicDataService#upInsertFamilyAndMember(java.util.List)
     */
    @Override
    public ImpDataResultVO upInsertFamilyAndMember(List<List<Object>> excelData)
            throws BaseAppException {
        StringBuilder errorResult = new StringBuilder();
        ImpDataResultVO resultVO = new ImpDataResultVO();
        int succ = 0, fail = 0, total = 0;
        if (Utils.isEmpty(excelData))
            throw ExceptionHandler.publish("APP-00-0033", "文件内容为空！");
        for (int i = 0; i < excelData.size(); i++) {
            StringBuilder oneError = new StringBuilder();
            try {
                List<Object> lo = excelData.get(i);

                if (Utils.isEmpty(String.valueOf(lo.get(1)))
                        || !"内蒙古自治区".equals(String.valueOf(lo.get(0)))) {
                    continue;
                }

                // 动作
                String fiAction = ACTIONADD, fmAction = ACTIONADD;
                total++;

                String villageName = String.valueOf(lo.get(4));
                String familyCode = String.valueOf(lo.get(5));
                String personCode = String.valueOf(lo.get(6));
                String name = String.valueOf(lo.get(7));
                String genderName = String.valueOf(lo.get(8));
                String idNumber = String.valueOf(lo.get(9));
                Integer personNum = Integer
                        .parseInt(String.valueOf(lo.get(10)));
                String masterRelName = String.valueOf(lo.get(11));
                String nationName = String.valueOf(lo.get(12));
                String educationLevelName = String.valueOf(lo.get(13));
                String studentStateName = String.valueOf(lo.get(14));
                String healthStateName = String.valueOf(lo.get(15));
                String workSkillName = String.valueOf(lo.get(16));
                String workStateName = String.valueOf(lo.get(17));
                Integer workMonths = Utils.isEmpty(String.valueOf(lo.get(18))) ? null
                        : Integer.parseInt(String.valueOf(lo.get(18)));
                // String isInsuranceName = String.valueOf(lo.get(19));
                String isNrcmsName = String.valueOf(lo.get(19));
                String isEndowmentName = String.valueOf(lo.get(20));
                String isCityEndowmentName = String.valueOf(lo.get(21));
                String povertyStateName = String.valueOf(lo.get(22));
                String povertyAttrName = String.valueOf(lo.get(23));
                String mainReasonName = String.valueOf(lo.get(24));
                BigDecimal avgIncome = Utils
                        .isEmpty(String.valueOf(lo.get(25))) ? null
                        : new BigDecimal(String.valueOf(lo.get(25)));
                String tel = String.valueOf(lo.get(26));
                String bankName = String.valueOf(lo.get(27));
                String accountCode = String.valueOf(lo.get(28));

                FamilyInfoPO familyInfoPO = new FamilyInfoPO();
                FamilyMemberPO familyMemberPO = new FamilyMemberPO();

                // 转换码表
                if (Utils.isEmpty(StaticDataUtil.villageInfoMap
                        .get(villageName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "行政村",
                            villageName));
                }
                else {
                    familyInfoPO.setVillageId(StaticDataUtil.villageInfoMap
                            .get(villageName));
                }

                FamilyInfoPO qryFamilyInfoPO = new FamilyInfoPO();
                qryFamilyInfoPO.setFamilyCode(familyCode);
                List<FamilyInfoPO> existFamilyInfo = familyInfoService
                        .selectByArg(qryFamilyInfoPO);
                if (null != existFamilyInfo && existFamilyInfo.size() > 0) {
                    fiAction = ACTIONUPDATE;
                    familyInfoPO.setFamilyId(existFamilyInfo.get(0)
                            .getFamilyId());
                }

                FamilyMemberPO qryFamilyMemberPO = new FamilyMemberPO();
                qryFamilyMemberPO.setIdNumber(idNumber);
                List<FamilyMemberPO> existFamilyMember = familyMemberService
                        .selectByArg(qryFamilyMemberPO);
                if (null != existFamilyMember && existFamilyMember.size() > 0) {
                    fmAction = ACTIONUPDATE;
                    familyMemberPO.setFamilyMemeberId(existFamilyMember.get(0)
                            .getFamilyMemeberId());
                }

                if (Utils.isEmpty(StaticDataUtil.genderNameMap.get(genderName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "性别",
                            genderName));
                }
                else {
                    familyMemberPO.setGender(StaticDataUtil.genderNameMap
                            .get(genderName));
                }

                if (Utils.isEmpty(StaticDataUtil.masterRelNameMap
                        .get(masterRelName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "与户主关系",
                            masterRelName));
                }
                else {
                    familyMemberPO
                            .setMasterRel((StaticDataUtil.masterRelNameMap
                                    .get(masterRelName)));
                }

                if (Utils.isEmpty(StaticDataUtil.nationNameMap.get(nationName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "民族",
                            nationName));
                }
                else {
                    familyMemberPO.setNation(StaticDataUtil.nationNameMap
                            .get(nationName));
                }

                if (Utils.isEmpty(StaticDataUtil.educationLevelNameMap
                        .get(educationLevelName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "文化程度",
                            educationLevelName));
                }
                else {
                    familyMemberPO
                            .setEducationLevel(StaticDataUtil.educationLevelNameMap
                                    .get(educationLevelName));
                }

                if (Utils.isEmpty(StaticDataUtil.studentStateNameMap
                        .get(studentStateName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "在校生状况",
                            studentStateName));
                }
                else {
                    familyMemberPO
                            .setStudentState(StaticDataUtil.studentStateNameMap
                                    .get(studentStateName));
                }

                if (Utils.isEmpty(StaticDataUtil.healthStateNameMap
                        .get(healthStateName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "健康状况",
                            healthStateName));
                }
                else {
                    familyMemberPO
                            .setHealthState(StaticDataUtil.healthStateNameMap
                                    .get(healthStateName));
                }

                if (Utils.isEmpty(StaticDataUtil.workSkillNameMap
                        .get(workSkillName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "劳动能力",
                            workSkillName));
                }
                else {
                    familyMemberPO.setWorkSkill(StaticDataUtil.workSkillNameMap
                            .get(workSkillName));
                }

                if (Utils.isEmpty(StaticDataUtil.workStateNameMap
                        .get(workStateName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "务工状况",
                            workStateName));
                }
                else {
                    familyMemberPO.setWorkState(StaticDataUtil.workStateNameMap
                            .get(workStateName));
                }

                if (Utils.isEmpty(StaticDataUtil.isNrcmsNameMap
                        .get(isNrcmsName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "是否参加新农合",
                            isNrcmsName));
                }
                else {
                    familyInfoPO.setIsNrcms(StaticDataUtil.isNrcmsNameMap
                            .get(isNrcmsName));
                }

                if (Utils.isEmpty(StaticDataUtil.isEndowmentNameMap
                        .get(isEndowmentName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.",
                            "是否参加新型养老保险", isEndowmentName));
                }
                else {
                    familyInfoPO
                            .setIsEndowment(StaticDataUtil.isEndowmentNameMap
                                    .get(isEndowmentName));
                }

                if (Utils.isEmpty(StaticDataUtil.isCityEndowmentNameMap
                        .get(isCityEndowmentName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.",
                            "是否参加城镇职工基本养老保险", isCityEndowmentName));
                }
                else {
                    familyMemberPO
                            .setIsCityEndowment(StaticDataUtil.isCityEndowmentNameMap
                                    .get(isCityEndowmentName));
                }

                if (Utils.isEmpty(StaticDataUtil.povertyStateNameMap
                        .get(povertyStateName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "脱贫属性",
                            povertyStateName));
                }
                else {
                    familyInfoPO
                            .setPovertyState(StaticDataUtil.povertyStateNameMap
                                    .get(povertyStateName));
                }

                if (Utils.isEmpty(StaticDataUtil.povertyAttrNameMap
                        .get(povertyAttrName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "贫困户属性",
                            povertyAttrName));
                }
                else {
                    familyInfoPO
                            .setPovertyAttr(StaticDataUtil.povertyAttrNameMap
                                    .get(povertyAttrName));
                }

                if (Utils.isEmpty(StaticDataUtil.mainReasonNameMap
                        .get(mainReasonName))) {
                    oneError.append(String.format("列【%s】,错误值【%s】.", "主要致贫原因",
                            mainReasonName));
                }
                else {
                    familyInfoPO.setMainReason(StaticDataUtil.mainReasonNameMap
                            .get(mainReasonName));
                }

                if("户主".equals(masterRelName)){
                    familyMemberPO.setMemberType(0);
                }else{
                    familyMemberPO.setMemberType(1);
                }
                familyMemberPO.setPersonCode(personCode);
                familyMemberPO.setName(name);
                familyMemberPO.setIdNumber(idNumber);
                familyMemberPO.setWorkMonths(workMonths);
                familyInfoPO.setFamilyCode(familyCode);
                familyInfoPO.setPersonNum(personNum);
                
                familyInfoPO.setAvgIncome(avgIncome);
                familyMemberPO.setTel(tel);
                familyMemberPO.setBankName(bankName);
                familyMemberPO.setAccountCode(accountCode);

                // 如果校验不通过，跳过
                if (Utils.notEmpty(oneError.toString())) {
                    errorResult.append("第" + (i + 1) + "数据行,校验失败:")
                            .append(oneError).append("\n").append("<br>");
                    fail++;
                    continue;
                }

                // 执行更新操作
                if (ACTIONADD.equals(fiAction)) {
                    // 新增，家庭信息
                    int fi_pkId = familyInfoService.add(familyInfoPO);
                    familyInfoPO.setFamilyId(fi_pkId);
                }
                else {
                    // 更新
                    familyInfoService.update(familyInfoPO);
                }

                familyMemberPO.setFamilyId(familyInfoPO.getFamilyId());

                if (ACTIONADD.equals(fmAction)) {
                    // 新增，家庭信息
                    int fm_pkId = familyMemberService.add(familyMemberPO);
                }
                else {
                    // 更新
                    familyMemberService.update(familyMemberPO);
                }

                succ++;
            }
            catch (Exception e) {
                logger.error("导入贫困户信息时发生异常，解析到第" + (i + 1) + "数据行，", e);
                errorResult.append(
                        "解析到第" + (i + 1) + "数据行时发生异常，异常信息：" + e.getMessage())
                        .append("<br>");
                fail++;
            }
            finally {

            }

        }
        resultVO.setCode(0);
        resultVO.setTotal(total);
        resultVO.setSucc(succ);
        resultVO.setFail(fail);
        resultVO.setErrorMsg(errorResult.toString());

        // return "导入完成，成功行数:"+succ+"失败行数:"+fail+".\n"+errorResult.toString();
        return resultVO;
    }

    /*
     * (non-Javadoc)
     * @see com.teamall.web.xtgl.service.IBasicDataService#updateFamilyInfo(com.teamall.web.family.db.po.FamilyInfoPO)
     */
    @Override
    public int updateFamilyInfo(FamilyInfoPO record) {

        return customFamilyAndMemberDao.updateFamilyInfo(record);
    }

    /*
     * (non-Javadoc)
     * @see com.teamall.web.xtgl.service.IBasicDataService#updateFamilyMember(com.teamall.web.family.db.po.FamilyMemberPO)
     */
    @Override
    public int updateFamilyMember(FamilyMemberPO record) {

        return customFamilyAndMemberDao.updateFamilyMember(record);
    }

    /*
     * (non-Javadoc)
     * @see com.teamall.web.xtgl.service.IBasicDataService#selectCodeFamilyInfoPOByArgAndPage(com.teamall.web.fpgz.db.po.CodeFamilyInfoPO,
     * com.teamall.core.common.Page, boolean, java.lang.Integer)
     */
    @Override
    public Page<CodeFamilyInfoPO> selectCodeFamilyInfoPOByArgAndPage(
            CodeFamilyInfoPO record, Page<CodeFamilyInfoPO> resultPage,
            boolean isInclude, Integer projectId) {
        CustomCodeFamilyInfoArg arg = new CustomCodeFamilyInfoArg();
        arg.setInclude(isInclude);
        arg.setProjectId(projectId);
        CodeFamilyInfoCriteria criteria = arg.createCriteria();
        if (Utils.notEmpty(record.getTownId())) {
            criteria.andTownIdEqualTo(record.getTownId());
            arg.setHasArg(true);
        }
        
        if (Utils.notEmpty(record.getVillageId())) {
            criteria.andVillageIdEqualTo(record.getVillageId());
            arg.setHasArg(true);
        }
        if (Utils.notEmpty(record.getVillageName())) {
            criteria.andVillageNameLike(record.getVillageName());
            arg.setHasArg(true);
        }

        if (Utils.notEmpty(record.getFamilyId())) {
            criteria.andFamilyIdEqualTo(record.getFamilyId());
            arg.setHasArg(true);
        }

        if (Utils.notEmpty(record.getPersonName())) {
            criteria.andPersonNameLike(record.getPersonName());
            arg.setHasArg(true);
        }
        if (Utils.notEmpty(record.getAidMainStaff())) {
            criteria.andAidMainStaffEqualTo(record.getAidMainStaff());
            arg.setHasArg(true);
        }
        resultPage = customFamilyAndMemberDao
                .selectCodeFamilyInfoPOByArgAndPage(arg, resultPage);

        return resultPage;
    }

}
